package com.rao.gmall.feign;

import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author nzmxfan
 * @create 2021-08-17-19:51
 */
@Configuration
public class AppFeignConfig {

    /**
     * feign 的拦截器
     *  作用：每次远程发请求的时候，都会尝试给新的request带上请求头
     * @return
     */

    //    RequestInterceptor headerRequestInterceptorX(){
//        RequestInterceptor interceptor = new RequestInterceptor() {
//            @Override
//            public void apply(RequestTemplate template) {
//                //得到上次的请求
//                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//                HttpServletRequest request = requestAttributes.getRequest();
//
//                //从前面的请求头里面获取到核心信息
//                String userId = request.getHeader("userId");
//                String userTempId = request.getHeader("userTempId");
//                template.header("userId",userId);
//                template.header("userTempId",userTempId);
//            }
//        };
//        return interceptor;
//    }

    @Bean
    public RequestInterceptor headerRequestInterceptor(){
        return (template)->{
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            // 有些请求未携带 userId 、userTempId，避免出现不必要的异常
            if(requestAttributes != null){
                HttpServletRequest request = requestAttributes.getRequest();
                // 从前面的请求头里面获取到核心信息
                String userId = request.getHeader("userId");
                String userTempId = request.getHeader("userTempId");
                template.header("userId",userId);
                template.header("userTempId",userTempId);
            }
        };
    }
}
